//
//  BTCourseDetial.m
//  BaxTer
//
//  Created by wsj2015 on 16/9/2.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "BTCommentCell.h"
#import "BTCourseDetailHeader.h"
#import "BTCourseDetailVC.h"
#import "MTTHeaderFooterFittingHeight.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "BTNoreplayCell.h"
#import "MPOpenReplyViewController.h"
#import "MJRefresh.h"
#import "ReaderFileViewController.h"
#import "HYBBubbleTransition.h"
#import "HZPhotoBrowser.h"
#import "WSJPopview.h"
#import "GzwTableViewLoading.h"
#import "TYVideoPlayerController.h"
#import "VideoPlayerViewController.h"
#import "JCAlertView.h"
#import "BTCourseModel.h"
#import "HELPDFfileCacheTool.h"
#import "RLMCourseManager.h"
#import "BTBaseWebVC.h"
#import "SSPopup.h"


@interface BTCourseDetailVC () <UITableViewDelegate, UITableViewDataSource,HZPhotoBrowserDelegate>

//@property(weak, nonatomic) IBOutlet UITableView *tableView;

@property(nonatomic, strong) BTCourseDetailHeader *header;

@property (nonatomic,  strong)HYBBubbleTransition* bubbleTransition ;

@property (nonatomic,  strong) BTCourseModel *courseDetail;


@end

@implementation BTCourseDetailVC



-(void)loadView
{
   
    self.view = self.header;

}


- (void)viewDidLoad {
  [super viewDidLoad];
    
  
    weakSelf_define;
 
   [self.header.scrollView  wsj_HeaderRefreshBlock:^{
        [weakSelf getCourseDetail];
   }];
//    [self getCourseDetail];
    
}


- (BTCourseDetailHeader *)header {
  if (!_header) {
    _header = [BTCourseDetailHeader deatilHeader];
    weakSelf_define;
    _header.pageBack = ^() {

      [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    
      
      _header.dowloadBlock =^(){
          
        
          WSJPopview *downPop = [[WSJPopview sharedWsjPopView] showDownLoadWithCourse:weakSelf.courseDetail];
          downPop.doneBlock = ^(){
             //刷新界面
              weakSelf.header.model = weakSelf.courseDetail;
              
              //更新数据库
            [[RLMCourseManager manager] creatOrUpdateCourse:weakSelf.courseDetail];
            
          };
          
      };
      _header.beginLearn = ^(){
          
//          weakSelf.header.ableTotest = YES;
//
          switch ([weakSelf.courseDetail.courseType integerValue]) {
              case 0:
                    [weakSelf gotoPdfVCWith:weakSelf.header];
                  break;
              case 1:
                  [weakSelf gotoVideo];
                  break;
              case 2: {
                  BTBaseWebVC *vc =[BTBaseWebVC new];
                  vc.course = weakSelf.courseDetail;
                  NSString *baseUrl = [[BTNetworkManager sharedMg] getBaseUrl];
                  //拼接id
                  NSString *url = [NSString stringWithFormat:@"%@/%@/%@",baseUrl,kMiniCourseUrl,weakSelf.courseDetail.id];
                  vc.url = url;
                  [weakSelf.navigationController setNavigationBarHidden:NO animated:YES];
                  [weakSelf.navigationController pushViewController:vc animated:YES];
          
                   }
                  break;
              case 3: //长图
                  [weakSelf browserPic];
                  break;
                  
              default:
                  break;
          }
          
         
          
          //wsjtest
         // [weakSelf gotoVideo];
      
      };
      _header.ratingBlock = ^(){
          //
          NSInteger type = [weakSelf.courseDetail.courseStatus integerValue];
          switch (type) {
                  
                  // 未完成 0  未学完1  待评分2 待测试3     已学完4
              case 0: //未开始
              case 1:  //待测试
              case 3:  //未学完
              {
                  [JCAlertView showTwoButtonsWithTitle:nil Message:@"亲，对不起您还没有学完课程不能进行评分哦！！" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"取消" Click:^{
                      
                  } ButtonType:JCAlertViewButtonTypeMainColor ButtonTitle:@"马上学习" Click:^{
                      //学习
                      weakSelf.header.beginLearn();
                  }];

                  
                  break;
            }
              case 4://已完成  显示评分
                  [[WSJPopview sharedWsjPopView] showRatingView:NO withHelpScore:[weakSelf.courseDetail.courseCScore floatValue] withContentScore:[weakSelf.courseDetail.courseHScore floatValue] withDoneBlock:nil];
                  
                  break;
             
              case 2://待评分
                  [[WSJPopview sharedWsjPopView] showRatingView:YES withHelpScore:0 withContentScore:0 withDoneBlock:^(CGFloat help_score, CGFloat content_score) {
                        [weakSelf postPriseOrCollectOrRatingWithCollect:-1 withPrise:-1 withRatingContent_score:help_score RatingHelp_score:content_score withBtn:nil];
                      
                  }];
                break;
            
             
              }
      
      };
      _header.testBlock = ^(){
          
//          [weakSelf pickTestItemsWithDataArray:@[@"考试1",@"考试2",@"考试3",@"考试4",@"考试5"]];
          [weakSelf queryTheTestlist];

        };
      _header.collectBlock  = ^(UIButton *btn){
          
       
          [weakSelf postPriseOrCollectOrRatingWithCollect:!btn.selected withPrise:-1 withRatingContent_score:-1 RatingHelp_score:-1 withBtn:btn];
      };
      _header.priseBlock = ^(UIButton *btn){
          
          [weakSelf postPriseOrCollectOrRatingWithCollect:-1 withPrise:!btn.selected withRatingContent_score:-1 RatingHelp_score:-1 withBtn:btn];
      };
     
  }
  return _header;
}

#pragma -mark 根据课程id 查询考试列表

- (void)queryTheTestlist{
    
    weakSelf_define;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"查询中..";
    [hud show:YES];
    NSString *url = [NSString stringWithFormat:@"%@/%@",KgetExamlist,self.courseDetail.id];
    [[BTNetworkManager sharedMg] GET:url parameters:nil success:^(NSArray * responseObject) {
        [hud hide:YES];
        if ([responseObject isKindOfClass:[NSArray class]]) {
            if (responseObject.count == 0) {
                alertMessage(@"该课程没有相关考试~");
                return ;
            }
            [weakSelf pickTestItemsWithDataArray:responseObject];
        }
        
    } failure:^(NSString *err) {
        [hud hide:YES];
    }];
    
}


#pragma -mark 请求是否能考试
- (void)queryIfAbleToTestWithExamId:(NSInteger)examId{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"查询中..";
    [hud show:YES];
    weakSelf_define;
    NSString *url = [NSString stringWithFormat:@"%@/%@",kIfhaveTestUrl,@(examId)];
    [[BTNetworkManager sharedMg] GET:url parameters:nil success:^(NSDictionary * responseObject) {
         [hud hide:YES];
        if (responseObject_success) {
            //进入考试
            [weakSelf gotoTestHtml5WithExamId:examId];
          
        }
        if (responseObject_Err) {
            alertMessage(responseObject[@"err"]);
        }
    } failure:^(NSString *err) {
          [hud hide:YES];
    }];

}



#pragma -mark 弹出考试列表
- (void)pickTestItemsWithDataArray:(NSArray *)listArray {
  
    weakSelf_define;
    
   
    NSMutableArray *strArr = [NSMutableArray array];
    [listArray enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[NSDictionary class]]) {
            if (obj[@"title"]) {
                [strArr addObject:obj[@"title"]];
            }
        }

        
    }];
    SSPopup* selection=[[SSPopup alloc]init];
    selection.backgroundColor=[UIColor colorWithWhite:0.00 alpha:0.4];
    
    selection.frame = CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height);
   
    [self.view  addSubview:selection];
    
    [selection CreateTableview:strArr withSender:nil  withTitle:@"考试选择" setCompletionBlock:^(int tag){
        
        WSJLog(@"Tag--->%d",tag);
        NSDictionary *dict = listArray[tag];
        if ([dict isKindOfClass:[NSDictionary class]]) {
            NSInteger examId =  [dict[@"id"] integerValue];
            [weakSelf queryIfAbleToTestWithExamId:examId];
        }
        
    }];
}

//浏览图片
- (void)browserPic{
    weakSelf_define;
    //启动图片浏览器
    HZPhotoBrowser *browserVc = [[HZPhotoBrowser alloc] init];
    browserVc.course = self.courseDetail;
    browserVc.sourceImagesContainerView = weakSelf.view; // 原图的父控件
    browserVc.imageCount = 1; // 图片总数
    browserVc.currentImageIndex = 0;
    browserVc.courseName= self.courseDetail.courseName;
    browserVc.courseUrl = self.courseDetail.courseUrl;
    browserVc.delegate = self;
    [browserVc showWithVC:weakSelf];
}



#pragma mark - photobrowser代理方法
- (UIImage *)photoBrowser:(HZPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
{
    return [UIImage imageNamed:@"longimage.png"];
}
- (NSURL *)photoBrowser:(HZPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index{
    if ([self.courseDetail.courseType integerValue] == 3) {
        return [NSURL URLWithString:self.courseDetail.courseUrl];
    }
    return nil;
}

#pragma -mark 进入考试界面
- (void)gotoTestHtml5WithExamId:(NSInteger)examId{
    BTBaseWebVC *vc =[BTBaseWebVC new];
    NSString *baseUrl = [[BTNetworkManager sharedMg] getBaseUrl];
    //拼接id
    NSString *url = [NSString stringWithFormat:@"%@/%@/%@",baseUrl,kStartExam,@(examId)];
    vc.url = url;
    vc.tagKey = @"exam";
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController pushViewController:vc animated:YES];

    

}

- (void)viewWillDisappear:(BOOL)animated {

  [super viewWillDisappear:animated];

 
}

- (void)configUI {

 

//  [self.tableView registerNib:[UINib nibWithNibName:@"BTCommentCell" bundle:nil]
//       forCellReuseIdentifier:@"BTCommentCell"];
//    self.tableView.tableFooterView = [UIView new];
//    [self.tableView registerNib:[UINib nibWithNibName:@"BTNoreplayCell" bundle:nil]
//         forCellReuseIdentifier:@"BTNoreplayCell"];
//  [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
//    make.left.equalTo(self.view);
//    make.top.equalTo(self.view).offset(-20);
//    make.right.equalTo(self.view);
//    make.bottom.equalTo(self.view);
//  }];


//  [self.tableView addLegendHeaderWithRefreshingBlock:^{
//      [self requestCommentData];
//  }];
  weakSelf_define;
    
//    self.header.beginLearn = ^(){
//    
//        //[weakSelf gotoPdfVCWith:weakSelf.header];
//      
//    
//    };
//  self.header.clickBlock = ^(BOOL isExpend, UILabel *contentLable) {
//    if (isExpend == YES) {
//      [weakSelf.tableView mtt_updateTableHeaderViewHeightWithConfig:^(id view) {
//        contentLable.text = @"mtt_updateTableHeaderViewHeightWithAnimatedmtt_"
//                            @"updateTableHeaderViewHeightWithAnimatedmtt_"
//                            @"updateTableHeaderViewHeightWithAnimatedmtt_"
//                            @"updateTableHeaderViewHeightWithAnimatedmtt_"
//                            @"updateTableHeaderViewHeightWithAnimatedmtt_"
//                            @"updateTableHeaderViewHeightWithAnimatedmtt_"
//                            @"updateTableHeaderViewHeightWithAnimated";
//        contentLable.numberOfLines = 0;
//      }
//                                                           animated:YES];
//    } else {
//      [weakSelf.tableView mtt_updateTableHeaderViewHeightWithConfig:^(id view) {
//        contentLable.text = @"mtt_updateTableHeader";
//        contentLable.numberOfLines = 1;
//      }
//                                                           animated:YES];
//    }
//   
//
//      
//  };
    
//    self.header.titleL.text = @"盖盖的自我修养";
//    self.header.contentLabel.text =@"女儿要买个十六块的文具盒，我给了她二十块，一起去买，路上她又要买气球，“今天气球四块钱卖不卖，我刚好只有四块钱额！”女儿居然会还价了。“行！”平时都是五块钱一个的，小孩子还价好玩，小贩笑着摘气球给她，一转头，看到她手上捏着的二十元大钞，愣了半天才说，“不是只有四块钱吗？”“是啊！快点找钱！”女儿一个劲催促。";
//   self.tableView.tableHeaderView = self.header;
//  [self.tableView mtt_updateTableHeaderViewHeightWithAnimated:NO];
//  self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
//    self.header.ableTotest = NO;
    
    
}

- (void)gotoVideo {
    // 测试用
//    [BTNetworkManager sharedMg];
   TYVideoPlayerController *playerController = [[TYVideoPlayerController alloc]init];
    playerController.videoTitle = self.courseDetail.courseName;
    NSString *path = [HELPDFfileCacheTool isChchedWithPdfFilename:self.courseDetail.courseName isMP4:YES];
    
    playerController.course = self.courseDetail;
    if (path) {
      NSURL *url = [NSURL fileURLWithPath:path];
      playerController.streamURL =  url;
    }else{
      playerController.streamURL = [NSURL URLWithString:self.courseDetail.courseUrl];
    }

 
    [self presentViewController:playerController animated:YES completion:nil];
//    
   // VideoPlayerViewController *playvc = [VideoPlayerViewController new];
    //[self presentViewController:playvc animated:YES completion:nil];

}

- (void)gotoPdfVCWith:(UIView *)cell{
    
    ReaderFileViewController *fileViewController = [[ReaderFileViewController alloc] init];
    //
//    
    fileViewController.title = self.courseDetail.courseName;
  
    fileViewController.course = self.courseDetail;
   
    fileViewController.modalPresentationStyle = UIModalPresentationFullScreen;
    defineWeakSelf;
    fileViewController.callBack = ^(){
        
        //刷新当前页面
        [weakSelf getCourseDetail];
        
    };
    
    /*
       测试代码
     */
    fileViewController.title = self.courseDetail.courseName;
    
    
  
   
    /*
    __weak typeof(_bubbleTransition) weakBubbleTransition = _bubbleTransition;
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>8.0) {
        navigationController.modalPresentationStyle = UIModalPresentationCustom;
        _bubbleTransition =[[HYBBubbleTransition alloc] initWithPresented:^(UIViewController *presented, UIViewController *presenting, UIViewController *source, HYBBaseTransition *transition) {
            // You need to cast type to the real subclass type.
            HYBBubbleTransition *bubble = (HYBBubbleTransition *)transition;
            
            // If you want to use Spring animation, set to YES.
            // Default is NO.
            //    bubble.animatedWithSpring = YES;
            bubble.bubbleColor = kMainColor;
            //                      bubble.animatedWithSpring = YES;
            // 由于一个控制器有导航，一个没有，导致会有64的误差
            CGPoint startPoint = [cell convertPoint:cell.center toView:self.view];
            startPoint.y +=64;
            bubble.bubbleStartPoint = startPoint;
        } dismissed:^(UIViewController *dismissed, HYBBaseTransition *transition) {
            
            transition.transitionMode = kHYBTransitionDismiss;
            navigationController.transitioningDelegate = nil;
        }];
    
        navigationController.transitioningDelegate =  weakBubbleTransition;
        
    }
    */
    
    [self presentViewController:fileViewController animated:YES completion:NULL];
    
    
    
}


- (IBAction)inputNew:(id)sender {
    
  
        //
    MPOpenReplyViewController *vc = [[MPOpenReplyViewController alloc]init];
    vc.bgImg = [self screenShot];
    weakSelf_define;
    vc.doneBlock = ^(NSString *content ,BOOL isHidenName){
       WSJLog(@"%@----%@",content,@(isHidenName));
    
        //请求数据
     
    };
    [self presentViewController:vc animated:NO completion:nil];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self getCourseDetail];
}

#pragma -mark 请求详情数据
- (void)getCourseDetail{
   
    if (!self.courseDetail) {
        [self wsj_showLodingGif];
    }
    weakSelf_define;

    [[BTNetworkManager sharedMg] POST:kGetCourseDetail parameters:@{@"id":@(self.courseId)} success:^(NSDictionary * responseObject) {
        
        if (!weakSelf.courseDetail) {
           
            if (!weakSelf.courseDetail && responseObject_Err) {
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
         
        }
    
        [weakSelf.header.scrollView.header endRefreshing];
        if (responseObject_success) {
            
            
            if ([responseObject[@"data"] isKindOfClass:[NSNull class]]) {
                [weakSelf.navigationController popViewControllerAnimated:YES];
                [weakSelf wsj_hideLodingGif];
                cwqAlertMessage(@"没查到相关课程~");
                return;
                
            }
            [weakSelf wsj_hideLodingGif];
            //这里关于训练营的 一次请求 
            if (weakSelf.traingCampDict && [weakSelf.traingCampDict[@"finished"] boolValue] == NO && [weakSelf.courseDetail.courseStatus integerValue] == 4) {
                
                [weakSelf postServerCampstepFinishedWithID:[weakSelf.traingCampDict[@"id"] integerValue]];
            }
            
            
            weakSelf.courseDetail =[BTCourseModel mj_objectWithKeyValues:responseObject[@"data"]];
            weakSelf.header.model = weakSelf.courseDetail;
         
            BOOL isMP4 = NO;
            if ([weakSelf.courseDetail.courseType integerValue] == 1) {
                isMP4 = YES;
            }
            //如果有下载过这条数据 就更新数据库
            if ([HELPDFfileCacheTool isChchedWithPdfFilename:weakSelf.courseDetail.courseName isMP4:isMP4]) {
                //更新数据库
                [[RLMCourseManager manager] creatOrUpdateCourse:weakSelf.courseDetail];
            }
            
        }
        
        
    } failure:^(NSString *err) {
          [weakSelf.header.scrollView.header endRefreshing];
        if (!weakSelf.courseDetail) {
           [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    }];
    

}

- (void)dealloc{


}

- (void)postServerCampstepFinishedWithID:(NSInteger)campStepId{

    weakSelf_define;
    NSString *url =[NSString stringWithFormat:@"%@/%@",kPostCourseHasFinished,@(campStepId)];
     [[BTNetworkManager sharedMg] GET:url parameters:nil success:^(id responseObject) {
         if (responseObject_success) {
             weakSelf.traingCampDict[@"finished"] = @(YES);
         }
     } failure:^(NSString *err) {
         
     }];
    
    
}


- (void)postPriseOrCollectOrRatingWithCollect:(NSInteger)collect withPrise:(NSInteger)prise withRatingContent_score:(CGFloat)content_s RatingHelp_score:(CGFloat)help_s withBtn:(UIButton *)btn{
    
    
    
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"请稍后...";
    if (collect != -1) {
        params[@"iscollect"] = @(collect);
        [hud show:YES];
    }
    if (prise != -1) {
        params[@"islike"] = @(prise);
        [hud show:YES];
    }
    if (content_s != -1 && help_s !=-1) {
        params[@"courseHScore"] = @(content_s);
        params[@"courseCScore"] = @(help_s);
        
    }
    params[@"courseID"] =@([self.courseDetail.id integerValue]);
    weakSelf_define;
    __block UIButton * bbtn =btn;
    [[BTNetworkManager sharedMg] POST:kPriseOrCollectOrRating parameters:params success:^(NSDictionary *responseObject) {
        [hud hide:YES];
        if (responseObject_success) {
            if (content_s != -1 && help_s !=-1) {
                //wsjtest
             
                if ([responseObject[@"data"] isKindOfClass:[NSString class]]) {
                    cwqAlertMessage(responseObject[@"data"]);
                    [weakSelf getCourseDetail];
                }
            }
            if (collect !=-1 || prise !=-1) {
                bbtn.selected = !bbtn.selected;
                
            }
        }
      
        
    } failure:^(NSString *err) {
        [hud hide:YES];
    }];
}


-(UIImage *)screenShot{
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(window.frame.size.width,window.frame.size.height), YES, 0);
    
    //设置截屏大小
    [[window layer] renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return  viewImage;
    
    
}

@end
